<template>
  <div class="login-page">
    <div class="login-title">欢迎回来 <span>👋</span></div>
    <div class="login-desc">请输入您的账号和密码以登录系统。</div>
    <van-field v-model="email" label="账号" placeholder="输入账号" clearable />
    <van-field 
      v-model="password" 
      label="密码" 
      placeholder="输入密码" 
      :type="showPwd ? 'text' : 'password'" 
      clearable 
      :right-icon="showPwd ? 'eye-o' : 'closed-eye'" 
      @click-right-icon="showPwd = !showPwd" 
    />
    <div class="login-options">
      <van-checkbox v-model="remember">记住密码</van-checkbox>
      <span class="forget" @click="onForget">忘记密码?</span>
    </div>
    <div class="register-tip">
      还没有账号？<span class="register-link" @click="onRegister">立即注册</span>
    </div>
    <van-button block type="primary" class="login-btn" @click="onLogin">立即登录</van-button>
    <van-dialog v-model:show="showDialog" title="登录成功！" show-cancel-button>
      <div style="text-align:center;">请稍候，登录成功后将跳转至首页。</div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, Dialog } from 'vant'
import { db, STORES } from '../../utils/db'

const router = useRouter()
const email = ref('')
const password = ref('')
const remember = ref(false)
const showPwd = ref(false)
const showDialog = ref(false)

const TEST_EMAIL = 'user'
const TEST_PWD = '123456'

const onLogin = async () => {
  if (!email.value || !password.value) {
    showToast('请输入邮箱和密码')
    return
  }
  
  try {
    // 从 IndexedDB 获取用户列表
    const userList = await db.getAll(STORES.USER_LIST)
    const user = userList.find(u => (u.account === email.value && u.password === password.value))
    
    if (user) {
      // 使用 localStorage 存储登录状态和用户基本信息
      localStorage.setItem('isLogin', 'true')
      localStorage.setItem('userName', user.username)
      localStorage.setItem('userEmail', user.account)
      
      // 不再存储头像到 localStorage
      if (remember.value) {
        localStorage.setItem('userPwd', user.password)
      } else {
        localStorage.removeItem('userPwd')
      }
      
      showDialog.value = true
      setTimeout(() => {
        showDialog.value = false
        router.replace('/home')
      }, 1200)
      return
    }
    
    // 默认测试账号
    if (email.value === TEST_EMAIL && password.value === TEST_PWD) {
      try {
        // 保存测试账号到 IndexedDB
        const testUser = {
          username: '测试用户',
          account: email.value,
          password: password.value,
          avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',
          starList: [],
          gender: '男',
          age: '',
          height: '',
          weight: '',
          targetWeight: '',
          activityLevel: ''
        }
        
        await db.put(STORES.USER_LIST, testUser)
        
        // 设置登录状态
        localStorage.setItem('isLogin', 'true')
        localStorage.setItem('userName', '测试用户')
        localStorage.setItem('userEmail', email.value)
        
        if (remember.value) {
          localStorage.setItem('userPwd', password.value)
        } else {
          localStorage.removeItem('userPwd')
        }
        
        showDialog.value = true
        setTimeout(() => {
          showDialog.value = false
          router.replace('/home')
        }, 1200)
      } catch (error) {
        console.error('保存测试账号失败:', error)
        showToast('登录失败，请重试')
      }
    } else {
      showToast('账号或密码错误')
    }
  } catch (error) {
    console.error('登录失败:', error)
    showToast('登录失败，请重试')
  }
}
const onForget = () => {
  showToast('请联系管理员')
}
const onRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: #fafaff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 24px;
}
.login-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #222;
  text-align: left;
  width: 100%;
}
.login-desc {
  font-size: 14px;
  color: #888;
  margin-bottom: 24px;
  width: 100%;
  text-align: left;
}
.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin: 8px 0 0 0;
}
.forget {
  color: #7c5dfa;
  font-size: 13px;
  cursor: pointer;
}
.register-tip {
  margin: 18px 0 18px 0;
  font-size: 13px;
  color: #888;
  width: 100%;
  text-align: left;
}
.register-link {
  color: #7c5dfa;
  cursor: pointer;
  margin-left: 4px;
}
.login-btn {
  background: #7c5dfa;
  border-radius: 18px;
  margin-top: 12px;
  font-size: 16px;
  font-weight: bold;
}
</style>
